package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.domain.vo.PlatformLLearnFrontVO;
import com.ruoyi.teaching.domain.vo.PlatformLLearnVO;
import com.ruoyi.teaching.mapper.*;
import com.ruoyi.teaching.service.PlatformLLearnService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-07-05
 */
@Service
public class PlatformLLearnServiceImpl extends ServiceImpl<PlatformLLearnMapper, PlatformLLearn> implements PlatformLLearnService {

    @Autowired
    private PlatformLLearnMapper platformLLearnMapper;

    @Autowired
    private PlatformCCourseMapper platformCCourseMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PlatformUVirtualMapper platformUVirtualMapper;

    @Autowired
    private PlatformCSpecialtyMapper platformCSpecialtyMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private RedisCache redisCache;

    private static final String VIRTUAL_SIMULATION_KEY = "learning:virtual";
    private static final String COURSE_KEY = "learning:course";

    /**
     *
     * @param pageNum           页码
     * @param pageSize          条数
     * @param learnType         学习类别（0虚拟仿真，1在线授课）
     * @param choose            筛选条件（虚拟仿真下0全部，1PC，2VR，3AR，4MR。在线授课下0全部，1专业授课，2云课堂）
     * @return
     */
    @Override
    public AjaxResult listOwn(Integer pageNum, Integer pageSize, Integer learnType, Integer choose) {
        int userId = SecurityUtils.getUserId().intValue();

        // 构建查询条件
        QueryWrapper<PlatformLLearn> queryWrapper = new QueryWrapper<>();
        if (learnType != null) {
            queryWrapper.eq("learn_type", learnType);
        }
        queryWrapper.eq("learn_person_id", userId);

        // 执行查询
        List<PlatformLLearn> allPlatformLLearns = platformLLearnMapper.selectList(queryWrapper);
        List<PlatformLLearnVO> platformLLearnVOS = new ArrayList<>();

        // 遍历查询结果并进行处理
        for (PlatformLLearn collect : allPlatformLLearns) {
            PlatformLLearnVO platformLLearnVO = new PlatformLLearnVO();
            BeanUtils.copyProperties(collect, platformLLearnVO);

            if (collect.getLearnType() == 0) {
                // 虚拟仿真处理
                handleVirtualLearn(collect, platformLLearnVO, choose);
            } else if (collect.getLearnType() == 1) {
                // 在线授课处理
                handleOnlineCourse(collect, platformLLearnVO, choose);
            }
            if(null != platformLLearnVO.getProjectName()){
                platformLLearnVOS.add(platformLLearnVO);
            }
        }

        // 进行分页处理
        int total = platformLLearnVOS.size();
        int start = Math.min((pageNum - 1) * pageSize, total);
        int end = Math.min(start + pageSize, total);
        List<PlatformLLearnVO> paginatedList = platformLLearnVOS.subList(start, end);

        // 创建分页对象
        Page<PlatformLLearnVO> collectVOPage = new Page<>(pageNum, pageSize);
        collectVOPage.setRecords(paginatedList);
        collectVOPage.setTotal(total);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", collectVOPage);
    }

    /**
     * 虚拟仿真处理逻辑
     */
    private void handleVirtualLearn(PlatformLLearn collect, PlatformLLearnVO platformLLearnVO, Integer choose) {
        Integer virtualId = collect.getProjectId();
        PlatformUVirtual platformUVirtual = platformUVirtualMapper.selectById(virtualId);
        if (platformUVirtual == null) {
            return;
        }

        String virtualType = platformUVirtual.getVirtualType();
        Integer[] virtualTypeArray = UniversalUtil.stringToArray(virtualType, Integer::valueOf, Integer.class);

        // 根据条件筛选
        if (choose != null) {
            int targetValue = -1;
            switch (choose) {
                case 1: targetValue = 0; break;
                case 2: targetValue = 1; break;
                case 3: targetValue = 3; break;
                case 4: targetValue = 2; break;
            }
            if (targetValue != -1 && (virtualTypeArray == null || !ArrayUtils.contains(virtualTypeArray, targetValue))) {
                return;
            }
        }

        // 设置虚拟仿真相关信息
        platformLLearnVO.setProjectName(platformUVirtual.getVirtualName());
        platformLLearnVO.setPersonName(platformUVirtual.getCreateBy());
        platformLLearnVO.setLearnImage(platformUVirtual.getResourceImage());
        platformLLearnVO.setVirtualType(virtualTypeArray);

        Integer professionalCategoryId = platformUVirtual.getProfessionalCategoryId();
        PlatformCSpecialty platformCSpecialty = platformCSpecialtyMapper.selectById(professionalCategoryId);
        if (platformCSpecialty != null) {
            platformLLearnVO.setDeptName(platformCSpecialty.getSpecialtyName());
        }
        platformLLearnVO.setTopDeptName(platformUVirtual.getUploadPersonSchool());
    }

    /**
     * 在线授课处理逻辑
     */
    private void handleOnlineCourse(PlatformLLearn collect, PlatformLLearnVO platformLLearnVO, Integer choose) {
        Integer courseId = collect.getProjectId();
        PlatformCCourse platformCCourse = platformCCourseMapper.selectById(courseId);
        if (platformCCourse == null) {
            return;
        }

        // 根据选择条件筛选课程
        if (choose != null) {
            if (choose == 1 && platformCCourse.getCourseVisible() != 1) {
                return;
            } else if (choose == 2 && platformCCourse.getCourseVisible() != 0) {
                return;
            }
        }

        // 设置课程相关信息
        platformLLearnVO.setProjectName(platformCCourse.getCourseName());
        platformLLearnVO.setLearnImage(platformCCourse.getCourseImage());
        platformLLearnVO.setCourseVisible(platformCCourse.getCourseVisible());
        platformLLearnVO.setCourseStatus(platformCCourse.getCourseStatus());

        // 设置专业信息
        Integer professionalCategoryId = platformCCourse.getProfessionalCategoryId();
        PlatformCSpecialty platformCSpecialty = platformCSpecialtyMapper.selectById(professionalCategoryId);
        if (platformCSpecialty != null) {
            platformLLearnVO.setDeptName(platformCSpecialty.getSpecialtyName());
        }

        // 设置用户信息
        platformLLearnVO.setPersonName(platformCCourse.getCreateBy());

        // 获取顶级部门信息
        long createId = platformCCourse.getCreateId().longValue();
        String topLevelSchoolName = UniversalUtil.findTopLevelSchoolName(sysUserRoleMapper, sysDeptMapper, sysUserMapper, createId);
        if (!"".equals(topLevelSchoolName)) {
            platformLLearnVO.setTopDeptName(topLevelSchoolName);
        }
    }


    @Override
    public AjaxResult insertPlatformLLearn(PlatformLLearn platformLLearn) {
        // 获取用户ID，如果无法获取则捕获异常
        int userId ;
        try {
             userId = SecurityUtils.getUserId().intValue();
        } catch (ServiceException e) {
            // 无法获取用户ID时，直接返回空
            return new AjaxResult(HttpStatus.SUCCESS,"请先登录");
        }
        UniversalCreateUpdate create = UniversalUtil.getCreateUpdate(sysUserMapper);
        Integer id = create.getId();
        platformLLearn.setCreateId(id);
        platformLLearn.setCreateTime(DateUtils.getNowDate());
        platformLLearn.setCreateBy(create.getName());
        platformLLearn.setLearnPersonId(Long.valueOf(id));

        //如果数据库中已经有该学习记录，不执行添加操作，只更新学习时间
        QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
        platformLLearnQueryWrapper.eq("learn_person_id", id).eq("project_id", platformLLearn.getProjectId()).eq("learn_type", platformLLearn.getLearnType());
        List<PlatformLLearn> platformLLearns = platformLLearnMapper.selectList(platformLLearnQueryWrapper);
        if(CollectionUtils.isNotEmpty(platformLLearns)){
            PlatformLLearn platformLLearn1 = platformLLearns.get(0);
            platformLLearn1.setUpdateTime(DateUtils.getNowDate());
            platformLLearn1.setUpdateBy(create.getName());
            platformLLearn1.setUpdateId(id);
            platformLLearnMapper.updateById(platformLLearn1);
            insertOnlineInfo(platformLLearn,userId);
            return new AjaxResult(HttpStatus.SUCCESS, "该"+ (platformLLearn1.getLearnType() == 0 ? "虚拟仿真":"课程") +"记录已更新");
        }

        int insert = platformLLearnMapper.insert(platformLLearn);
        if (insert > 0) {
            insertOnlineInfo(platformLLearn,userId);
            return new AjaxResult(HttpStatus.SUCCESS, "添加成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "添加失败");
        }
    }

    private void insertOnlineInfo(PlatformLLearn platformLLearn, Integer userId) {
        String redisKey = platformLLearn.getLearnType() == 0 ? VIRTUAL_SIMULATION_KEY : COURSE_KEY;
        redisCache.setCacheSetValue(redisKey, userId);
    }

    @Override
    public AjaxResult deletelearnByIds(Long[] ids) {
        int length = ids.length;
        int deleteCount = platformLLearnMapper.deleteBatchIds(Arrays.asList(ids));
        if (deleteCount == length) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "删除失败");
        }
    }

    /**
     * 获取项目学习信息
     *
     * @param projectId 项目ID
     * @param learnType 学习类型
     * @return 查询结果
     */
    @Override
    public AjaxResult getLearnByProjectId(Integer projectId, Integer learnType) {
        // 创建查询条件
        QueryWrapper<PlatformLLearn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId).eq("learn_type", learnType).orderByDesc("update_time").orderByDesc("create_time");

        // 查询符合条件的学习信息
        List<PlatformLLearn> platformLLearns = platformLLearnMapper.selectList(queryWrapper);

        // 过滤掉重复的学习者ID，只保留最新的记录
        List<PlatformLLearn> distinctLearns = platformLLearns.stream()
                .filter(UniversalUtil.distinctByKey(PlatformLLearn::getLearnPersonId))
                .collect(Collectors.toList());

        // 将PlatformLLearn对象转换为PlatformLLearnFrontVO对象并补充用户信息
        List<PlatformLLearnFrontVO> platformLLearnFrontVOS = distinctLearns.stream()
                .map(platformLLearn -> {
                    PlatformLLearnFrontVO platformLLearnFrontVO = new PlatformLLearnFrontVO();
                    BeanUtils.copyProperties(platformLLearn, platformLLearnFrontVO);

                    // 查询学习者的用户信息
                    SysUser user = sysUserMapper.selectUserById(platformLLearn.getLearnPersonId());
                    if (user != null) {
                        platformLLearnFrontVO.setAvatar(user.getAvatar());
                        platformLLearnFrontVO.setNickName(user.getNickName());
                    }

                    return platformLLearnFrontVO;
                }).collect(Collectors.toList());

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformLLearnFrontVOS);
    }
}
